package hoodoos.rule.script.jython;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;

public final class Files {

  private Files() {
  }

  public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
    return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
  }

  public static List<String> readLines(File file, Charset charset) throws IOException {
    try (BufferedReader reader = newReader(file, charset)) {
      return reader.lines().collect(Collectors.toList());
    }
  }

  public static String readAsString(File file, Charset charset) throws IOException {
    try (BufferedReader reader = newReader(file, charset)) {
      return reader.lines().collect(Collectors.joining("\n"));
    }
  }

  public static String readAsString(String filePath, Charset charset) throws IOException {
    File file = new File(filePath);
    return readAsString(file, charset);
  }

  public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
    return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
  }

  public static void write(File file, String content, Charset charset) throws IOException {
    BufferedWriter bufferedWriter = newWriter(file, charset);
    bufferedWriter.write(content);
    bufferedWriter.flush();
    bufferedWriter.close();
  }
}
